package org.zjkoye.crm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zjkoye.crm.common.PageResultBean;
import org.zjkoye.crm.common.Result;
import org.zjkoye.crm.entity.Workorder;
import org.zjkoye.crm.service.WorkorderService;
import org.zjkoye.crm.utils.ThreadLocalUtil;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/workorder")
public class WorkorderController {

    private static final Logger logger = LoggerFactory.getLogger(WorkorderController.class);

    @Autowired
    private WorkorderService workorderService;

    @GetMapping("/pageList")
    @Operation(summary = "工单列表分页查询")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "pageSize", required = true, description = "每页显示的条数"),
            @Parameter(name = "currentPage", required = true, description = "要查询的页"),
            @Parameter(name = "status", description = "工单状态", required = false)
    })
    public Result<PageResultBean<Workorder>> pageList(@RequestParam int pageSize, @RequestParam int currentPage, @RequestParam(required = false) String status) {

        IPage<Workorder> page = workorderService.pageList(pageSize, currentPage, status);
        if (page == null) {
            return Result.error("查询失败");
        }
        PageResultBean<Workorder> pageResultBean = new PageResultBean<>(page.getTotal(), page.getRecords());
        logger.info(String.valueOf(pageSize));
        return Result.success(PageResultBean.getInstance(page.getTotal(), page.getRecords()));
    }

    @PostMapping("/add")
    @Operation(summary = "添加工单")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<String> addWorkorder(@RequestBody Workorder workorder) {

        // 设置操作人
        Map<String, Object> userSession = ThreadLocalUtil.get();
        String operator = (String) userSession.get("name");
        workorder.setOperator(operator);

        // 判断业务ID
        if (workorder.getBusinessId() == null || workorder.getBusinessId() == 0) {
            return Result.error("添加失败，业务ID不能为空");
        }

        // 判断状态
        if (!"未派单".equals(workorder.getStatus()) &&
                !"已派单".equals(workorder.getStatus()) &&
                !"已收单".equals(workorder.getStatus()) &&
                !"已回单".equals(workorder.getStatus())) {
            return Result.error("添加失败，工单状态无效");
        }

        boolean isSuccess = workorderService.save(workorder);
        if (isSuccess) {
            return Result.success("工单添加成功");
        } else {
            return Result.error("工单添加失败");
        }
    }

    @PutMapping("/update")
    @Operation(summary = "修改工单信息")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<String> updateWorkorder(@RequestBody Workorder workorder) {
        // 检查工单ID
        if (workorder.getWorkOrderId() == null || workorder.getWorkOrderId() == 0) {
            return Result.error("工单ID无效");
        }

        // 设置更新者
        Map<String, Object> userSession = ThreadLocalUtil.get();
        String operator = (String) userSession.get("name");
        workorder.setOperator(operator);

        boolean isSuccess = workorderService.updateById(workorder);
        if (isSuccess) {
            return Result.success("工单修改成功");
        } else {
            return Result.error("工单修改失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除工单信息")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "id", required = true, description = "工单id")
    })
    public Result<String> deleteWorkorder(@PathVariable int id) {
        boolean result = workorderService.removeById(id);
        if (!result) {
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }

    @GetMapping("/getById")
    @Operation(summary = "根据id查询工单信息")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "id", required = true, description = "工单id")
    })
    public Result<Workorder> getWorkorderById(@RequestParam int id) {
        Workorder workorder = workorderService.getById(id);
        if (workorder == null) {
            return Result.error("获取工单信息失败");
        }
        return Result.success(workorder);
    }

    @PostMapping("/assign")
    @Operation(summary = "派单")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<String> assignWorkOrder(@RequestBody Workorder workorder) {
        if (workorder.getWorkOrderId() == null || workorder.getWorkOrderId() == 0) {
            return Result.error("工单ID无效");
        }
        workorder.setStatus("已派单");

        boolean isSuccess = workorderService.updateById(workorder);
        if (isSuccess) {
            return Result.success("派单成功");
        } else {
            return Result.error("派单失败");
        }
    }

    @PostMapping("/receive")
    @Operation(summary = "收单")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<String> receiveWorkOrder(@RequestBody Workorder workorder) {
        if (workorder.getWorkOrderId() == null || workorder.getWorkOrderId() == 0) {
            return Result.error("工单ID无效");
        }
        workorder.setStatus("已收单");

        boolean isSuccess = workorderService.updateById(workorder);
        if (isSuccess) {
            return Result.success("收单成功");
        } else {
            return Result.error("收单失败");
        }
    }

    @GetMapping("/unassigned")
    @Operation(summary = "获取未派单工单")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<PageResultBean<Workorder>> getUnassignedWorkOrders(@RequestParam int pageSize, @RequestParam int currentPage) {
        IPage<Workorder> page = workorderService.getUnassignedWorkOrders(pageSize, currentPage);
        if (page == null) {
            return Result.error("查询失败");
        }
        PageResultBean<Workorder> pageResultBean = new PageResultBean<>(page.getTotal(), page.getRecords());
        return Result.success(pageResultBean);
    }

    @GetMapping("/assigned")
    @Operation(summary = "获取已派单工单")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<PageResultBean<Workorder>> getAssignedWorkOrders(@RequestParam int pageSize, @RequestParam int currentPage) {
        IPage<Workorder> page = workorderService.getAssignedWorkOrders(pageSize, currentPage);
        if (page == null) {
            return Result.error("查询失败");
        }
        PageResultBean<Workorder> pageResultBean = new PageResultBean<>(page.getTotal(), page.getRecords());
        return Result.success(pageResultBean);
    }

    @GetMapping("/operators")
    @Operation(summary = "获取操作员列表")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<List<String>> getOperators() {
        List<String> operators = workorderService.getOperators();
        if (operators == null || operators.isEmpty()) {
            return Result.error("获取操作员列表失败");
        }
        return Result.success(operators);
    }


    public void tobesame()
    {

    }

}
